from rest_framework import serializers
from drfstudy.models import Students, Classes


# 普通类  ===》 功能==》继承
# 学生序列化器
# class StudentSerializer(serializers.Serializer):
#     # read_only=True 只允许前端查看id 不能修改学生id 只读
#     # label 前端的备注信息
#     # required=False 允许为空
#     id = serializers.IntegerField(read_only=True,label='ID')
#     name = serializers.CharField(max_length=20,label='姓名')
#     age = serializers.IntegerField(required=False,label='年龄')
#     sex = serializers.IntegerField(required=False,label='性别')
#     create_time = serializers.DateTimeField(required=False,label='创建时间')
#     update_time = serializers.DateTimeField(required=False,label='修改时间')
#     is_delete = serializers.BooleanField(required=False,label='逻辑删除',default=False)
#
#     def create(self,validated_data):
#         return Students.objects.create(**validated_data)
#
#     def update(self,instance,validated_data):
#         # instance 原本模型数据
#         # validated_data  新数据
#         # 没有修改的 就还是 instance的原数据
#         instance.name = validated_data.get('name',instance.name)
#         instance.age = validated_data.get('age',instance.age)
#         instance.sex = validated_data.get('sex',instance.sex)
#         # 模型里面的save方法
#         instance.save()
#         # 返回更新后的数据
#         return instance

#模型序列化器


# class ClassSerializer(serializers.ModelSerializer):
#     #
#     # students_set = StudentSerializer(many=True,read_only=True)
#     class Meta:
#         model = Classes
#         fields = '__all__'
#         # exclude = ('is_delete',)

class StudentSerializer(serializers.ModelSerializer):

    classname = serializers.CharField(source="classes.name",read_only=True)

    # classes = ClassSerializer(read_only=True)

    class Meta:
        model = Students # 学生这个模型
        #fields 字段 '__all__'所有信息
        fields = '__all__'

        # exclude 限制不响应的数据
        # exclude = ('is_delete',)
        extra_kwargs = {
            #   设置限制字段
                "classes": {"write_only": True},
            #    设置年龄设置（规则）
            #     "age": {"min_value": 18, "max_value": 100},
        }

    #属性级别的校验
    #validate_xx --- xx为字段名
    # def validate_name(self, value):
    #     if 'jt' not in value:
    #         raise serializers.ValidationError("名字无jt")
    #     return value

    #对象级别的校验 多个字段的校验规则
    def validate(self, attrs):
        if 'jt' not in attrs.get('name'):
            raise serializers.ValidationError("名字无jt")
        if not(attrs.get('age') >=18 and attrs.get('age')<=100):
            raise serializers.ValidationError("年龄不符合(18-100),未成年不允许添加")
        return attrs



class ClassSerializer(serializers.ModelSerializer):
    #
    # students_set = StudentSerializer(many=True,read_only=True)
    class Meta:
        model = Classes
        fields = '__all__'
        # exclude = ('is_delete',)
